package gmed;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.io.*;
import java.sql.*;
import java.rmi.*;
import java.rmi.server.*;

public class Medico_Impl extends UnicastRemoteObject implements Medico {
	private int nlicenca;
	private String nome;
	private int idesp;
	private int idmedico;
	private static Connection conn = null;

	public Medico_Impl(int nlicenca) throws RemoteException {
		this.nlicenca = nlicenca;
		if (conn == null)
			conn = DBConnection2.get_conn();
		
		java.sql.Statement st;
		System.out.println(conn);
		try {
			st = conn.createStatement();
			java.sql.ResultSet rs = st.executeQuery("select nome,idesp,idmedico from medico where nlicenca="+nlicenca);
			if (rs.first()) { 
				this.nome = rs.getNString(1);
				this.idesp = rs.getInt(2);
				this.idmedico = rs.getInt(3);
			} else {
				if (st.execute("insert into medico (nlicenca) values ("+ nlicenca + ")", st.RETURN_GENERATED_KEYS)) 
				{
					rs = st.getGeneratedKeys();
					rs.first();
					this.idmedico = rs.getInt(1);

				}
				
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}

	public int get_nlicenca() throws RemoteException {
		return nlicenca;
	}

	public String get_nome() throws RemoteException {
		return this.nome;
	}

	public int get_especialidade() throws RemoteException {
		return idesp;
	}

	private void update_field(String field, Object Value) {
		Statement st;
		try {
			if (conn == null)
				conn = DBConnection2.get_conn();
			st = conn.createStatement();
			String query = "update medico set "+field+"='"+ Value.toString() + "' where nlicenca=" + this.nlicenca;
			st.execute(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void antes_eliminar(){
		Statement  st;
		try{
			if(conn==null)
				conn=DBConnection2.get_conn();
			st=conn.createStatement();
			String query="delete from receitas where receitas.idmedico=(select idmedico from medico where nlicenca="+this.nlicenca+")";
			st.execute(query);
		}catch(SQLException e){
			
		}
	}
	public void elimina_medico(int nlicenca){
		antes_eliminar();
		Statement st;
		try{
			if(conn==null)
				conn= DBConnection2.get_conn();
			st=conn.createStatement();
			String query="delete from medico where nlicenca="+this.nlicenca;
			st.execute(query);
		}catch (SQLException e){
	}
	}

	public boolean set_nome(String nome) throws RemoteException {
		this.nome = nome;
		this.update_field("nome", nome);
		return true;
	}

	public boolean set_especialidade(int especialidade)
			throws RemoteException {
		this.idesp = especialidade;
		this.update_field("idesp", especialidade);
		return true;
	}
}
